<template>
  <el-dialog
    v-model="visible"
    :title="!dataList[0].propId ? $t('crud.addTitle') : $t('temp.modify')"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      label-width="auto"
      @submit.prevent
    >
      <el-form-item :label="$t('tip.chooseLanguage')">
        <el-select
          ref="dataSelectRef"
          v-model="value1"
          multiple
          :placeholder="$t('tip.select')"
          style="width: 450px;"
          @change="selectChange()"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <p class="tips-txt">
          {{ $t('product.defaultChinese') }}
        </p>
      </el-form-item>

      <el-form-item :label="$t('product.attributeName')">
        <el-table
          :data="dataList"
          border
          style="width: 450px;"
          :show-header="false"
        >
          <el-table-column
            prop="propName"
            header-align="center"
            align="center"
            :label="$t('product.attributeName')"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.propName"
                :placeholder="$t('product.attributeName')"
                maxlength="10"
                show-word-limit
                clearable
                :disabled="!(value1[0]==='Cn'||value1[1]==='Cn')"
                @blur="scope.row.propName = handleInputSpaces(scope.row.propName, 0)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="propNameEn"
            header-align="center"
            align="center"
            :label="$t('product.attributeNameEn')"
          >
            <template #default="scope">
              <el-input
                v-if="(value1[0]==='En'||value1[1]==='En')"
                v-model="scope.row.propNameEn"
                placeholder="Attribute"
                clearable
                maxlength="10"
                show-word-limit
                @blur="scope.row.propNameEn = handleInputSpaces(scope.row.propNameEn, 0)
                "
              />
              <el-input
                v-else
                value=""
                placeholder="Attribute"
                clearable
                maxlength="10"
                show-word-limit
                :disabled="true"
              />
            </template>
          </el-table-column>
        </el-table>
        <p class="tips-txt">
          {{ $t('product.theAttribute') }}
        </p>
      </el-form-item>

      <el-form-item :label="$t('product.attributeValue')">
        <div
          class="default-btn primary-btn"
          @click="add"
        >
          {{ $t('product.additive') }}
        </div>
        <p class="tips-txt">
          {{ $t('product.theValue') }}
        </p>
      </el-form-item>

      <el-form-item>
        <el-table
          :data="prodPropValuesData"
          max-height="225px"
          :show-header="false"
          :border="false"
        >
          <el-table-column
            prop="propValue"
            :label="$t('product.attributeValueEn')"
            align="left"
            min-width="40%"
            show-overflow-tooltip
          >
            <template #default="scope">
              <el-input
                v-model="prodPropValuesData[scope.$index].propValue"
                maxlength="20"
                clearable
                :placeholder="$t('product.attributeValue')"
                :disabled="!(value1[0]==='Cn'||value1[1]==='Cn')"
                @blur="prodPropValuesData[scope.$index].propValue = handleInputSpaces(prodPropValuesData[scope.$index].propValue, 1)"
              />
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            min-width="40%"
            show-overflow-tooltip
            prop="propValueEn"
            :label="$t('product.attributeValue')"
          >
            <template #default="scope">
              <el-input
                v-if="(value1[0]==='En'||value1[1]==='En')"
                v-model="prodPropValuesData[scope.$index].propValueEn"
                clearable
                maxlength="20"
                placeholder="Value"
                @blur="prodPropValuesData[scope.$index].propValueEn = handleInputSpaces(prodPropValuesData[scope.$index].propValueEn, 1)"
              />
              <el-input
                v-else
                value=""
                clearable
                maxlength="20"
                placeholder="Value"
                :disabled="true"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="change"
            :label="$t('publics.operating')"
            align="left"
            min-width="20%"
            show-overflow-tooltip
          >
            <template #default="scope">
              <a
                href="javascript:;"
                @click="deleteRow(scope.$index)"
              >{{ $t('resource.Delete') }}</a>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])
const dataSelectRef = ref(null)

const visible = ref(false)
const dataList = ref([{ propId: 0, propName: '', propNameEn: '', prodPropValues: [{ valueId: 0 }] }])
const prodPropValuesData = ref([{ valueId: 0, propValue: '', propValueEn: '' }])
const isSubmit = ref(false)
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const options = [{
  value: 'Cn',
  label: '简体中文'
}, {
  value: 'En',
  label: 'En'
}]
const value1 = ref(['Cn'])

/**
 * 输入框纯空格处理
 */
const handleInputSpaces = (value, type) => {
  if (!value) return
  value = specInputLimit(value, type)
  return value.trim()
}
/**
 * 输入特殊字符处理
 */
const specInputLimit = (value, type) => {
  const reg = /[\\;\\:\\；\\：]/g
  const regVal = /[\\;\\；]/g
  if (reg.test(value) && type === 0) {
    ElMessage.error($t('product.doNotEnterSpecialCharacters') + ':;')
    return ''
  }
  if (regVal.test(value) && type === 1) {
    ElMessage.error($t('product.doNotEnterSpecialCharacters') + ';')
    return ''
  }
  return value
}

// 多选框默认选择中文
const selectChange = () => {
  if (value1.value.length === 1 && value1.value[0] !== 'Cn') {
    value1.value.unshift('Cn')
  }
  if (value1.value.length < 1) {
    value1.value.push('Cn')
  }
  // 只有中文时，移除英文的内容
  if (value1.value.length <= 1) {
    dataList.value[0].propNameEn = ''
    prodPropValuesData.value.forEach(item => {
      item.propValueEn = ''
    })
  }
}

// 表单提交
const onSubmit = () => {
  const temp = []
  if (prodPropValuesData.value) {
    for (const key in prodPropValuesData.value) {
      if (Object.prototype.hasOwnProperty.call(prodPropValuesData.value, key)) {
        const element = prodPropValuesData.value[key]
        if (element.propValue && element.propValue.trim()) {
          temp.push(prodPropValuesData.value[key])
        } else {
          ElMessage.error($t('product.specValueCannotBeEmpty'))
          return
        }
      }
    }
  }
  dataList.value[0].propName = dataList.value[0].propName || ''
  // 判断是否有相同的属性值
  const prodPropValues = prodPropValuesData.value
  if (prodPropValues) {
    for (let i = 0; i < prodPropValues.length - 1; i++) {
      if (!prodPropValues[i].propValue) {
        ElMessage.error($t('product.specTip').replace('N', i + 1))
        return
      }
      for (let j = i + 1; j < prodPropValues.length; j++) {
        if (prodPropValues[i].propValue === prodPropValues[j].propValue) {
          ElMessage.error($t('product.same'))
          return
        }
      }
    }
  }
  if (!dataList.value[0].propName) return ElMessage.error($t('product.attributeNameNoNull'))
  if (temp.length < 1) return ElMessage.error($t('product.specificationy'))
  if (isSubmit.value) return false
  isSubmit.value = true
  http({
    url: http.adornUrl('/prod/spec'),
    method: dataList.value[0].propId ? 'put' : 'post',
    data: http.adornData({
      propId: dataList.value[0].propId || undefined,
      propName: dataList.value[0].propName,
      propNameEn: dataList.value[0].propNameEn || dataList.value[0].propName,
      prodPropValues: prodPropValuesData.value
    })
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        visible.value = false
        dataSelectRef.value?.blur()
        emit('refreshDataList', page)
      }
    })
  }).catch(() => {
    isSubmit.value = false
  })
}

/**
 * 添加一行规格
 */
const add = () => {
  const temp = prodPropValuesData.value[0]
  if (temp.propValue) {
    prodPropValuesData.value.unshift({ propValue: '', propValueEn: '' })
  } else {
    ElMessage.error($t('product.specValueCannotBeEmpty'))
  }
}
/**
 * 删除一行规格
 */
const deleteRow = (index) => {
  if (prodPropValuesData.value.length <= 1) {
    ElMessage.error($t('product.attributeNotDel'))
    return
  }
  prodPropValuesData.value.splice(index, 1)
}

const init = (val) => {
  isSubmit.value = false
  if (val) {
    dataList.value = [JSON.parse(JSON.stringify(val))]
    prodPropValuesData.value = dataList.value[0].prodPropValues
  } else {
    dataList.value = [
      { propId: 0, propName: '', propNameEn: '', prodPropValues: [{ valueId: 0 }] }
    ]
    prodPropValuesData.value = [{ valueId: 0, propValue: '', propValueEn: '' }]
  }
  visible.value = true
}

defineExpose({ init })
</script>

<style lang="scss" scoped>
.tips-txt {
  font-size: 12px;
  color: #999999;
  line-height: 20px;
}

div :deep(.el-form-item__content) {
  display: block;
}
</style>
